package models

import (
	"github.com/astaxie/beego/orm"
)

type SysUser struct {
	Id                 int
	RealName           string `orm:"size(32)"`
	Username           string `orm:"size(24)" valid:"Required"`
	Password           string `json:"-"`
	IsSuper            bool
	Status             int
	Mobile             string            `orm:"size(16)"`
	Email              string            `orm:"size(50)"`
	Avatar             string            `orm:"size(150)"`
	RoleIds            []int             `orm:"-" form:"RoleIds"`
	RoleSysUserRel     []*RoleSysUserRel `orm:"reverse(many)"`
	ResourceUrlForList []string          `orm:"-"`
}

type SysUserQueryParam struct {
	BaseQueryParam
	UserNameLike string
	RealNameLike string
	Mobile       string
	SearchStatus string
}

func init() {
	orm.RegisterModel(new(SysUser))
}

func (a *SysUser) TableName() string {
	return SysUserTBName()
}

func SysUserTBName() string {
	return TableName("sys_user")
}

func SysUserPageList(params *SysUserQueryParam) ([]*SysUser, int64) {
	query := orm.NewOrm().QueryTable(SysUserTBName())
	data := make([]*SysUser, 0)

	sortorder := "Id"
	switch params.Sort {
	case "Id":
		sortorder = "Id"
	case "Used":
		sortorder = "tag"
	}

	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	query = query.Filter("username__istartswith", params.UserNameLike)
	query = query.Filter("realname__istartswith", params.RealNameLike)

	if len(params.Mobile) > 0 {
		query = query.Filter("mobile", params.Mobile)
	}

	if len(params.SearchStatus) > 0 {
		query = query.Filter("status", params.SearchStatus)
	}

	total, _ := query.Count()
	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&data)
	return data, total
}

func SysUserOne(id int) (*SysUser, error) {
	o := orm.NewOrm()
	m := SysUser{Id: id}
	err := o.Read(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}

// 根据用户名密码获取单条
func SysUserOneByUserName(username string) (*SysUser, error) {
	m := SysUser{}
	err := orm.NewOrm().QueryTable(SysUserTBName()).Filter("username", username).One(&m)
	if err != nil {
		return nil, err
	}
	return &m, nil
}
